<template>
  <div class="back-nav" @click="switchToRegister">
    <van-icon name="arrow-left" />
    <span style="font-size: 1.25rem">返回登录</span>
  </div>

  <div class="fw">
  </div>

  <div class="auth-box">
      <h2>用户注册</h2>
    <van-cell-group inset style="margin-bottom: 10px">
    <!--    <div class="input-group">-->
      <van-dropdown-menu>
        <van-dropdown-item
            v-model="registForm.userType"
            :options="option"
        />
      </van-dropdown-menu>
      <van-field
          v-model="registForm.userNumber"
          name="工号"
          label="工&nbsp;&nbsp;&nbsp;&nbsp;号"
          placeholder="请输入工号"
          label-align="left"
          :rules="[{ required: true, message: '请填写工号' }]"
          size="large"
      />
      <van-field
          v-model="registForm.userName"
          name="昵称"
          label="昵&nbsp;&nbsp;&nbsp;&nbsp;称"
          placeholder="请输入昵称"
          label-align="left"
          :rules="[{ required: true, message: '请填写昵称' }]"
          size="large"
      />
      <van-field
          v-model="registForm.password"
          label="密&nbsp;&nbsp;&nbsp;&nbsp;码"
          name="密码"
          placeholder="请输入密码"
          label-align="left"
          type="password"
          :rules="[{ required: true, message: '请输入密码' }]"
          size="large"
      />
      <van-field
          v-model="registForm.confirmPassword"
          name="确认密码"
          label="密&nbsp;&nbsp;&nbsp;&nbsp;码"
          placeholder="请再次输入密码"
          label-align="left"
          type="password"
          :rules="[{ required: true, message: '请再次输入密码' }]"
          size="large"
      />
      <van-field
          v-model="registForm.email"
          name="email"
          label="邮&nbsp;&nbsp;&nbsp;&nbsp;箱"
          placeholder="请输入邮箱"
          label-align="left"
          :rules="[{ required: true, message: '请输入邮箱' }]"
          size="large"
      />
<!--      <van-cell-group>-->
        <van-field
            v-model="registForm.verificationCode"
            center
            clearable
            label="验证码"
            placeholder="验证码"
            :rules="[{ required: true, message: '请输入邮箱' }]"
            size="large"
        >
          <template #button>
            <van-button
                size="small"
                type="primary"
                @click="sendVerificationCode"
                :disabled="registForm.countdown > 0 || !isValidEmail(registForm.email)"
            >
              {{ registForm.countdown > 0 ? `${registForm.countdown}秒` : '获取验证码' }}
            </van-button>
          </template>
        </van-field>
<!--      </van-cell-group>-->
    </van-cell-group>
<!--    </div>-->

    <van-checkbox
        v-model="registForm.checked"
        checked-color="#ee0a24"
        icon-size="small"
    >
      点击阅读并同意
      <span class="link-text" @click="showBusinessAgreement">《用户注册协议》</span>
      和
      <span class="link-text" @click="showPrivacyAgreement">《隐私协议》</span>
    </van-checkbox>

    <div class="button-container">
      <van-button
          :loading="registForm.loading"
          :disabled="isRegisterDisabled"
          type="primary"
          @click="handleRegister"
      >注册</van-button>
  </div>
  </div>
</template>


<script setup lang="ts" name="LoginView">
import { reactive, computed } from 'vue';
import { showDialog, showToast } from 'vant';
import { useRouter } from 'vue-router';
import { saveUsingPost, userRegisterUsingPost} from "../../Api/yonghumokuai";
import { useLoginStore } from '../../Store/modules/userinfo/LoginTZ';
import { agreements, AgreementType } from '../../Constants/agreements';

// 使用 store
const RegisterStore = useLoginStore();
// // 监听 activeTab 的变化
// console.log(RegisterStore.activeTab);

//切换到登陆页面
const switchToRegister = () => {
  RegisterStore.setActiveTab('login');
  // console.log(RegisterStore.activeTab)
};


const router = useRouter();

// 身份选择表单
const option = [
  { text: '领导', value: 1 },
  { text: '辅导员', value: 2 },
  { text: '教师', value: 3 },
];

// 注册表单
const registForm = reactive({
  userNumber: null,
  userName: '',
  password: '',
  userType: 3,
  confirmPassword: '',
  email: '',
  verificationCode: '',
  checked: false,
  loading: false,
  countdown: 0,
});

// 验证邮箱格式
const isValidEmail = (email: string) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

// 按钮禁用状态
const isRegisterDisabled = computed(() => {
  return !registForm.userNumber ||
      !registForm.password ||
      !registForm.confirmPassword ||
      !registForm.email ||
      !registForm.verificationCode ||
      !registForm.checked;
});

// 增加协议安全类型检查
const showBusinessAgreement = () => showAgreement('business');
const showPrivacyAgreement = () => showAgreement('privacy');

// 显示协议
function showAgreement(type: AgreementType) {
  const agreement = agreements[type];
  showDialog({
    title: agreement.title,
    message: agreement.content,
    confirmButtonText: '我已阅读'
  });
}

// 发送验证码
async function sendVerificationCode() {
  if (!isValidEmail(registForm.email)) {
    showToast('请输入正确的邮箱格式');
    return;
  }
  try {
    const response = await saveUsingPost({
      email: registForm.email,
    })
    const data = response.data
    if (data.code === 0) {
      showToast('验证码已发送');
      registForm.countdown = 60;
      const timer = setInterval(() => {
        registForm.countdown--;
        if (registForm.countdown <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    } else {
      showToast(data.message || '验证码发送失败');
    }
  } catch (error: any) {
    showToast(error.response?.data?.message || '验证码发送失败');
  }
}

// 注册处理
async function handleRegister() {
  if (!registForm.checked) {
    showDialog({
      message: '请同意用户协议和隐私协议',
    });
    return;
  }
  if (registForm.password !== registForm.confirmPassword) {
    showToast('两次输入的密码不一致');
    return;
  }
  if (registForm.password.length < 8) {
    showToast('密码长度不能小于8位');
    return;
  }
  if (registForm.userNumber.length < 10) {
    showToast('学号长度不能小于10位');
    return;
  }

  registForm.loading = true;
  try {
    const response = await userRegisterUsingPost({
      userNumber: registForm.userNumber,
      password: registForm.password,
      email: registForm.email,
      userName: registForm.userName,
      userType: registForm.userType,
      emailCode: registForm.verificationCode
    });
    if (response.data.code === 0) {
      showToast('注册成功');
      // 跳转登陆页面
      RegisterStore.setActiveTab('login');
    } else {
      showToast(response.data.message || '注册失败');
    }
  } catch (error: any) {
    showDialog({
      message: error.response?.data?.message || '注册失败，请重试！',
    });
  } finally {
    registForm.loading = false;
  }
}

</script>

<style scoped>
/* 第一层盒子样式 */
.auth-box {
  width: 82%;
  margin: 0 auto;
  padding: 15px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
}

/* 撑高盒子的样式 */
.fw {
  height: 15%;
}

/* 注册标题样式 */
h2 {
  font-size: 170%;
  font-weight: 400;
  margin: 15px 15px;
  color: #9a009a;
}

/*表单输入框长度*/
:deep(.van-cell) {
  width: 100%;
}

/* 链接文本的样式 */
.link-text {
  color: #747bff;
  cursor: pointer;
  display: inline-block;
  margin: 0 auto;
  transition: all 0.2s ease;;
}

.link-text:hover {
  opacity: 0.8;
  color: #7c2d7c;
  text-decoration: none;
}

/* 按钮容器的样式 */
.button-container {
  margin-top: 1%;
}

/* 下拉框基础样式 */
:deep(.van-dropdown-menu) {
  display: flex;
  max-height: 20%;
  margin-left: 3%;
  width: auto !important;
}

/* 下拉框初始样式 */
:deep(.van-dropdown-item) {
  max-width: 74%;
  max-height: 20%;
  margin-left: 13%;
  width: auto !important;
}

/*下拉框伸展展示底部样式*/
:deep(.van-overlay) {
  width: 30% !important;
  height: 30% !important;
}

/*菜单未展开样式*/
:deep(.van-dropdown-menu__bar, .van-dropdown-menu__bar--opened) {
  background-color: rgb(253, 253, 254) !important;
  box-shadow: none !important;
}

/* 下拉框伸展样式 */
:deep(.van-dropdown-item--down) {
  background-color: white !important;
}

/* 主按钮样式 */
:deep(.van-button--primary) {
  width: 100%;
  background-color: #800080;
  border: none;
}

/* 主按钮非禁用状态下的样式 */
:deep(.van-button--primary:not(:disabled)) {
  background-color: #800080;
}

/* 主按钮非禁用状态下的悬停效果 */
:deep(.van-button--primary:not(:disabled):hover) {
  background-color: #9a009a;
}

/* 主按钮禁用状态下的样式 */
:deep(.van-button--primary:disabled) {
  background-color: #cccccc;
  opacity: 0.6;
}

.header-with-back {
  height: 40px;
  padding: 10px;
  text-align: left;
  font-size: 20px;
  color: #682757;
  line-height: 40px;
  overflow: hidden;
  min-width: 100%;
  position: fixed;
  z-index: 999;
}

.back-nav {
  position: fixed;
  left: 1%;
  top: 1.25%;
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  color: rgb(83, 30, 88);
  padding: 0.5rem;
  z-index: 10;
  font-size: 0.9rem;
}

.header-with-back .van-icon {
  position: static;
  font-size: 1.35rem;
}

/*按钮*/
.button-container {
  margin: 10px auto;
  width: 90%;
}

/*复选框基础*/
:deep(.van-checkbox) {
  margin-left: 15px;
  font-size: 12px;
  padding-top: 5px;
  padding-bottom: 5px;
}
.van-icon {
  position: static;
  font-size: 1.35rem;
}

</style>




